// [1865]找出和为指定值的下标对
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
use std::collections::HashMap;
struct FindSumPairs {
    nums1: Vec<i32>,
    nums2: Vec<i32>,
    cnt_map: HashMap<i32, i32>,
}

/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl FindSumPairs {
    fn new(nums1: Vec<i32>, nums2: Vec<i32>) -> Self {
        let mut cnt_map = HashMap::new();
        for &x in &nums2 {
            cnt_map.entry(x).and_modify(|cnt| *cnt += 1).or_insert(1);
        }
        Self {
            nums1,
            nums2,
            cnt_map,
        }
    }

    fn add(&mut self, index: i32, val: i32) {
        let index = index as usize;
        self.cnt_map
            .entry(self.nums2[index])
            .and_modify(|cnt| *cnt -= 1);
        self.nums2[index] += val;
        self.cnt_map
            .entry(self.nums2[index])
            .and_modify(|cnt| *cnt += 1)
            .or_insert(1);
    }

    fn count(&self, tot: i32) -> i32 {
        let mut ans = 0;
        for &x in &self.nums1 {
            ans += self.cnt_map.get(&(tot - x)).unwrap_or(&0);
        }
        ans
    }
}

/**
 * Your FindSumPairs object will be instantiated and called as such:
 * let obj = FindSumPairs::new(nums1, nums2);
 * obj.add(index, val);
 * let ret_2: i32 = obj.count(tot);
 */
//leetcode submit region end(Prohibit modification and deletion)

#[test]
fn main() {
    let nums1 = vec![1, 1, 2, 2, 2, 3];
    let nums2 = vec![1, 4, 5, 2, 5, 4];
    let mut pair = FindSumPairs::new(nums1, nums2);
    assert_eq!(pair.count(7), 8);
    pair.add(3, 2);
    assert_eq!(pair.count(8), 2);
    assert_eq!(pair.count(4), 1);
    pair.add(0, 1);
    pair.add(1, 1);
    assert_eq!(pair.count(7), 11);

    let nums1 = vec![9, 70, 14, 9, 76];
    let nums2 = vec![26, 26, 58, 23, 74, 68, 68, 78, 58, 26];
    let mut pair = FindSumPairs::new(nums1, nums2);
    pair.add(6, 10);
    pair.add(5, 6);
    assert_eq!(pair.count(32), 2);
}
